package com.hu.example.domain.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.hu.core.jdbc.JDBCCallback;
import com.hu.core.jdbc.JDBCTemplate;
import com.hu.example.domain.model.User;

public class UserDao {
    private JDBCTemplate<User> template;

    public void setJdbcTemplate(JDBCTemplate<User> template) {
        this.template = template;
    }

    public User getUserByName(final String userName) {
        final String sqlString = "SELECT * from user WHERE user_name = ?";

        return template.queryOne(sqlString, new JDBCCallback<User>() {
            @Override
            public User toObject(ResultSet rs) throws SQLException {
                int id = rs.getInt("id");
                String userNameInDB = rs.getString("user_name");
                String passwordInDB = rs.getString("password");

                User user = new User();
                user.setId(id);
                user.setUserName(userNameInDB);
                user.setPassword(passwordInDB);
                return user;
            }

            @Override
            public void setParams(PreparedStatement pStatement) throws SQLException {
                pStatement.setString(1, userName);
            }
        });
    }
}